package com.canbot.u05.activity.vipguide;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.canbot.u05.MainApplication;
import com.canbot.u05.R;
import com.canbot.u05.activity.BaseActivityNoTitle;
import com.canbot.u05.bean.JsonResponse;
import com.canbot.u05.bean.VipPersonMapData;
import com.canbot.u05.bean.guide.LocalPointsBean;
import com.canbot.u05.socket.IpMsgConst;
import com.canbot.u05.socket.MsgSendUtils;
import com.canbot.u05.socket.MsgType;
import com.canbot.u05.utils.Logger;
import com.canbot.u05.utils.OkHttpUtils;
import com.canbot.u05.utils.PathConst;
import com.canbot.u05.utils.SPUtils;
import com.canbot.u05.utils.ToastTools;
import com.canbot.u05.view.CommonDialog;
import com.canbot.u05.widget.LoadingDialogUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

//默认设置时与修改时是同一张地图

/**
 * Created by cwf on 2017/5/25.
 * 贵宾引领地点设置
 */

public class SiteSettingActivity extends BaseActivityNoTitle implements View.OnClickListener, AdapterView.OnItemClickListener {

        private GridView gridViewSetting;

        private int selectedSiteIndex = -1;

        private SiteSettingGvAdapter vipSiteAdapter;

        private ToastTools toastTools;

        private ArrayList<LocalPointsBean> siteList;

        private Dialog dialogLoading;

        private TextView textView;

        private CommonDialog commonDialog = new CommonDialog(SiteSettingActivity.this);

        private String identification;

        private String isReception;

        private boolean isFirst;

        private String isSetting;

        private String mapRoute;

        private String route;

        private CommonDialog dialogCounsel;

        private List<VipPersonMapData> list = new ArrayList<>();

        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_vip_site_setting);

                toastTools = ToastTools.newInstance(this);
                isReception = getIntent().getStringExtra("isreception");
                isSetting=getIntent().getStringExtra("isSetting");
                identification=getIntent().getStringExtra("identification");
                mapRoute=getIntent().getStringExtra("mapRoute");
                isFirst=getIntent().getBooleanExtra("isFirst",false);
                route = SPUtils.getString(SiteSettingActivity.this,"receptionRoute",null);
                getMapData();

                setViews();
                if(TextUtils.isEmpty(isSetting)){
                        String[] voices = {"u052_scyl_001.wav","u052_scyl_002.wav"};
                        int index = (int) (Math.random() * voices.length);
                        MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.VIP_GUIDE_DIR + voices[index]);
                }
                getData();

        }

        /**
         * 所有贵宾引领点的集合
        * */
        private void getMapData() {
                HashMap<String, Object> hashMap = new HashMap<String, Object>();
                hashMap.put("vipType", "queryAllRoute");
                OkHttpUtils.upLoadFile("http://" + IpMsgConst.SOCKET_HOST2 +
                        ":7755/" + "routevipGuide", hashMap, new OkHttpUtils.OkHttpCallBack() {

                        @Override
                        public void onSuccess(String result) {
                                JsonResponse jsonResponse = JSON.parseObject(result, JsonResponse.class);
                                if (jsonResponse.getRc()==0) {
                                        String resultData = jsonResponse.getResult().toString();
                                        Logger.e("VipGuideTaskManageActivity", "resultData" + resultData);
                                        list = JSON.parseArray(resultData, VipPersonMapData.class);
                                        Logger.e("VipGuideTaskManageActivity", "list" + list);
                                }
                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                ToastTools.newInstance(SiteSettingActivity.this).showText(getString(R.string.network_request_failed));
                                        }
                                });
                        }
                });
        }
        private void setViews() {
                findViewById(R.id.imageView_back).setOnClickListener(this);
                findViewById(R.id.ok_btn).setOnClickListener(this);

                textView = (TextView) findViewById(R.id.text_tit);
                gridViewSetting = (GridView) findViewById(R.id.gv_vip_site_setting);
                vipSiteAdapter = new SiteSettingGvAdapter();
                gridViewSetting.setAdapter(vipSiteAdapter);
                gridViewSetting.setOnItemClickListener(this);
                if(!TextUtils.isEmpty(isReception)) {
                        textView.setText("接待地点");
                }
                if(isFirst) {
                        textView.setText("接待地点");
                }
        }
        private void playStartsound(){
                String[] voices = {"u05_ddsz_001.wav", "u05_ddsz_002.wav"};
                int index = (int) (Math.random() * voices.length);

                MsgSendUtils.sendStringMsg(MsgType.PLAY_SOUND, PathConst.VIP_GUIDE_DIR + voices[index]);
                MsgSendUtils.sendStringMsg(MsgType.EYE_MOTION, "32");
                MsgSendUtils.sendStringMsg(MsgType.ACTION, "14009");
        }


        private void getData() {

                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));
                String url = IpMsgConst.HTTP_URL_CHEST + "guideMapAction";
                HashMap<String, Object> hashMap = new HashMap<>();
                hashMap.put("type", 8 + "");
                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {


                        @Override
                        public void onSuccess(String result) {

                                Log.e("sitesettingactivity", result);
                                Log.e("sitesettingactivity", list.toString());

                                if (!TextUtils.isEmpty(result)) {
                                        Type gsonType = new TypeToken<ArrayList<LocalPointsBean>>() {
                                        }.getType();
                                        siteList = new Gson().fromJson(result, gsonType);
                                        for(int i=0;i<siteList.size();i++){
                                                if (!TextUtils.isEmpty(isReception)) {
                                                        if(list.size()==0 || list==null){
                                                                break;
                                                        }else{
                                                                for(int j=0;j<list.size();j++){
                                                                        if(siteList.get(i).getPointName().equals(list.get(j).getMapRoute())){
                                                                                siteList.remove(i);
                                                                                break;
                                                                        }
                                                                }
                                                        }

                                                }else{
                                                        if(siteList.get(i).getPointName().equals(route)){
                                                                siteList.remove(i);
                                                                break;
                                                        }
                                                }
                                        }
                                        vipSiteAdapter.setList(siteList);
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        cancelDialog();
                                                        vipSiteAdapter.notifyDataSetChanged();
                                                }
                                        });
                                }else{
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        cancelDialog();
                                                        commonDialog.warnDialog(new CommonDialog.OnEnsureListener() {
                                                                @Override
                                                                public void onEnsure(View view) {
                                                                        if(TextUtils.isEmpty(isSetting)){
                                                                                MainApplication.finishActivity(VipGuideTaskActivity.class.getName());
                                                                                MainApplication.finishActivity(VipGuideTaskManageActivity.class.getName());
                                                                        }else{
                                                                                commBack();
                                                                        }
                                                                        finish();

                                                                }
                                                        });
                                                }
                                        });
                                }

                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                cancelDialog();
                                                toastTools.showText(getString(R.string.network_error));
                                        }
                                });

                        }
                });


        }

        /**
         * 取消加载的Dialog
         */
        private void cancelDialog() {
                if (dialogLoading != null) {
                        if (dialogLoading.isShowing()) {
                                dialogLoading.cancel();
                        }
                }
        }

        public void onClick(View view) {
                switch (view.getId()) {
                        case R.id.ok_btn:
                                //todo 执行地点指引
                                if (selectedSiteIndex == -1) {
                                        //弹出对话框
                                        commonDialog.noDialog("当前选择不能为空！");
                                        return;
                                }
                                LocalPointsBean localPointsBean = siteList.get(selectedSiteIndex);

                                if(!TextUtils.isEmpty(isReception)){
                                        playStartsound();
                                        Logger.e("isReception","isReception");
                                        isReception=null;
                                        SPUtils.saveString(SiteSettingActivity.this,"receptionRoute",localPointsBean.getPointName());
                                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_RECEPTION_ROUTE, localPointsBean.getPointName());
                                        finish();
                                        return;

                                }
                                if(isFirst){
                                        playStartsound();
                                        Logger.e("isReception","isReception");
                                        isFirst=false;
                                        SPUtils.saveString(SiteSettingActivity.this,"receptionRoute",localPointsBean.getPointName());
                                        MsgSendUtils.sendStringMsgToPad(MsgType.SEND_RECEPTION_ROUTE, localPointsBean.getPointName());
                                        startActivity(new Intent(SiteSettingActivity.this,VipGuideActivity.class));
                                        finish();
                                        return;
                                }

                                if(TextUtils.isEmpty(isReception)){
                                        playStartsound();
                                        Logger.e("isReception","！！！！！isReception");
                                        updateRoute(identification,localPointsBean.getPointName());
                                }

                                break;
                        case R.id.imageView_back:
                                if (!TextUtils.isEmpty(isSetting)) {
                                        commBack();
                                }
                                finish();
                        default:
                                break;
                }
        }

        private void updateRoute(String identification,String mapRoute){
                dialogLoading = LoadingDialogUtils.createLoadingDialog(this, getResources().getString(R.string.request));
                String url = "http://" + IpMsgConst.SOCKET_HOST2 + ":7755/routevipGuide";
                HashMap<String, String> hashMap = new HashMap<>();

                hashMap.put("vipType", "updateRoute");
                hashMap.put("identification", identification);
                hashMap.put("route", mapRoute);

                Logger.e("isReception","route0000"+ route);

                OkHttpUtils.upLoadFile(url, hashMap, new OkHttpUtils.OkHttpCallBack() {
                        @Override
                        public void onSuccess(String result) {

                                final JsonResponse strMsgBean = JSON.parseObject(result, JsonResponse.class);
                                Logger.e("save", "onSuccess:" + "http://" + IpMsgConst.SOCKET_HOST + ":7755/" + "strMsgBean.getRc()" + strMsgBean.getRc());
                                if (strMsgBean.getRc() >= 0) {
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        dialogLoading.setCancelable(true);
                                                        cancelDialog();
                                                        ToastTools.newInstance(SiteSettingActivity.this).showText(getString(R.string.modify_successfully));
                                                        vipSiteAdapter.notifyDataSetChanged();
                                                        showbackdialog();
                                                        return;

                                                }
                                        });
                                }
                                else {
                                        runOnUiThread(new Runnable() {
                                                @Override
                                                public void run() {
                                                        cancelDialog();
                                                        ToastTools.newInstance(SiteSettingActivity.this).showText(getString(R.string.parameter_empty));
                                                        return;
                                                }
                                        });
                                }
                        }

                        @Override
                        public void onFailure() {
                                runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                                cancelDialog();
                                                ToastTools.newInstance(SiteSettingActivity.this).showText(getString(R.string.network_error));
                                        }
                                });
                        }
                });
        }

        private void showbackdialog(){
                dialogCounsel = new CommonDialog(SiteSettingActivity.this);
                dialogCounsel.warnDialog("贵宾任务设置成功！", new CommonDialog.OnEnsureListener() {
                        @Override
                        public void onEnsure(View view) {
                                commBack();
                                finish();
                        }
                });
        }

        public void commBack(){
                if (!TextUtils.isEmpty(isSetting)) {

                        MainApplication.finishActivity(KnowVipActivity.class.getName());
                        MainApplication.finishActivity(SetVipNameActivity.class.getName());
                        MainApplication.finishActivity(VipGuideConfirmActivity.class.getName());
                        MainApplication.finishActivity(WelcomeSettingActivity.class.getName());
                        if (!TextUtils.isEmpty(getIntent().getStringExtra("isChoose"))) {
                                MainApplication.finishActivity(VipGuideChooseVoiceActivity.class.getName());
                        }
                        else {
                                MainApplication.finishActivity(VipGuideTextToVoiceActivity.class.getName());
                        }
                        MainApplication.finishActivity(ReceptionSettingActivity.class.getName());
                        MainApplication.finishActivity(ReceptionSettingDanceActivity.class.getName());
                }
                MainApplication.finishActivity(VipGuideTaskActivity.class.getName());
                MainApplication.finishActivity(VipGuideTaskManageActivity.class.getName());
        }

        @Override
        protected void onPause() {
                super.onPause();
                cancelDialog();
                MsgSendUtils.sendStringMsg(MsgType.STOP_SOUND, "stop_sound");
        }

        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                selectedSiteIndex = i;
                vipSiteAdapter.notifyDataSetChanged();

                if (!TextUtils.isEmpty(isReception)) {
                        route = null;
                }
                if (!TextUtils.isEmpty(isSetting)) {
                        mapRoute = null;
                }
                if (TextUtils.isEmpty(isSetting) && TextUtils.isEmpty(isReception)) {
                        mapRoute = null;
                }

        }


        class SiteSettingGvAdapter extends BaseAdapter {

                public void setList(List<LocalPointsBean> list) {
                        this.list = list;
                }

                private List<LocalPointsBean> list;

                @Override
                public int getCount() {
                        return list == null || list.size() == 0 ? 0 : list.size();
                }

                @Override
                public Object getItem(int position) {
                        return list.get(position);
                }

                @Override
                public long getItemId(int position) {
                        return position;
                }

                @Override
                public View getView(int position, View convertView, ViewGroup parent) {
                        ViewHolder holder;
                        if (convertView == null) {
                                convertView = View.inflate(SiteSettingActivity.this, R.layout.gridview_vipguide_vipsitesetting, null);
                                holder = new ViewHolder();
                                holder.tvvipsite = (TextView) convertView.findViewById(R.id.tv_vip_site);

                                convertView.setTag(holder);
                        }
                        else {
                                holder = (ViewHolder) convertView.getTag();
                        }
                        LocalPointsBean item = (LocalPointsBean) getItem(position);
                        Log.e("PointName", item.getPointName());
                        holder.tvvipsite.setText(item.getPointName());
                        if(!TextUtils.isEmpty(isReception)){
                                if(list.get(position).getPointName().equals(route)){
                                        selectedSiteIndex=position;
                                        Log.e("isReception isReception", item.getPointName());
                                }
                        }
                        if(TextUtils.isEmpty(isSetting)){
                                if(list.get(position).getPointName().equals(mapRoute)){
                                        selectedSiteIndex=position;
                                        Log.e("isReception isSetting", item.getPointName());
                                }
                        }

                        if (position == selectedSiteIndex) {
                                holder.tvvipsite.setTextColor(android.graphics.Color.parseColor("#fc9146"));
                                holder.tvvipsite.setBackgroundResource(R.drawable.vipguide_site_textbg_press);
                        }
                        else {
                                holder.tvvipsite.setTextColor(android.graphics.Color.parseColor("#ffffff"));
                                holder.tvvipsite.setBackgroundResource(R.drawable.vipguide_site_textbg_nor);
                        }

                        return convertView;
                }

                class ViewHolder {

                        TextView tvvipsite;

                }
        }


}
